package com.tedu.sp02.controller;

import com.tedu.sp01.pojo.Item;
import com.tedu.sp01.service.ItemService;
import com.tedu.sp01.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {
    //注入业务对象
    @Autowired
    private ItemService itemService;
    //为了后面测试集群多台服务器，这里注入端口号
    @Value("${server.port}")
    private int port;
    //只处理get请求
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws Exception{
        log.info("orderId="+orderId+",port="+port);
        //添加随机延迟的代码,90%的概率会延迟
        if(Math.random()<0.9){
            //随机产生0到5000的随机延迟时长
            long t=new Random().nextInt(5000);
            log.info("item-service-"+port+"-pause");
            Thread.sleep(t);
        }
        List<Item> items=itemService.getItems(orderId);
        return JsonResult.ok().msg("port="+port).data(items);

    }
    //只处理post请求RequestBody注解是：完整接受请求协议体的数据，只有post才有请求协议体
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }
}
